﻿package net.libra.ui
{
	import net.libra.core.interfaces.IDestroy;
	
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	import net.libra.utils.ArrayUtil;

	/**
	 * 按钮群组
	 * @author elvisjiang
	 */
	public class ButtonGroup extends EventDispatcher implements IDestroy
	{
		private var allowNoSelection : Boolean;
		private var _btnList : Array;
		private var selectedBtn : EasyButton;

		/**
		 * 按钮群组
		 * @param allowNoSelection	是否允许组内不选择
		 */
		public function ButtonGroup(allowNoSelection : Boolean = true)
		{
			this.allowNoSelection = allowNoSelection;
			this._btnList = new Array( );
		}

		public function destroy():void
		{
			for each(var button:EasyButton in _btnList)
			{
				button.destroy();
				button = null;
			}
			_btnList.length = 0;
			selectedBtn = null;
		}
		
		public function get btnList():Array
		{
			return _btnList;
		}

		public function set btnList(value:Array):void
		{
			_btnList = value;
		}

		/**
		 * 添加按钮
		 * @param btn	要添加的按钮
		 */
		public function appendButton(btn : EasyButton) : void
		{
			if(this._btnList.indexOf(btn) == -1)
			{
				this._btnList.push(btn);
				btn.setGroup(this );
			}
		}

		/**
		 * 移除按钮
		 * @param btn	要移除的按钮
		 */
		public function removeButton(btn : EasyButton) : void
		{
			ArrayUtil.removeValueFromArray(_btnList,btn);
		}

		/**
		 * 设置选择
		 * @param selected		是否选中
		 * @param btn			要选中的按钮
		 */
		public function setSelected(selected : Boolean,btn : EasyButton) : void
		{
			if(this._btnList.indexOf(btn) == -1)return;
			//
			if(this.selectedBtn == btn)
			{
				return;
			}
			if(selected && this.selectedBtn != btn)
			{
				var oldSelection : EasyButton = this.selectedBtn;
				this.selectedBtn = btn;
				if(oldSelection)oldSelection.setSelected( false );
				if(this.selectedBtn)this.selectedBtn.setSelected( true );
			}else if(! selected && this.selectedBtn == btn && this.allowNoSelection)
			{
				this.selectedBtn = null;
			}
			if(selected == true)
				this.dispatchEvent(new SelectEvent(SelectEvent.SELECT,this._btnList.indexOf(btn)));
		}

		/**
		 * 查询按钮当前是否被选中
		 * @param btn		要查询的按钮
		 * @return			按钮当前是否被选中
		 */
		internal function isSelected(btn : EasyButton) : Boolean
		{
			return this.selectedBtn === btn;
		}

		public function getSelectedBtn() : EasyButton
		{
			return this.selectedBtn;
		}

		public function setAllowNoSelection(allowNoSelection : Boolean) : void
		{
			this.allowNoSelection = allowNoSelection;
		}

		public function isAllowNoSelection() : Boolean
		{
			return this.allowNoSelection;
		}
	}
}
